package com.joinway.admin.platform;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HsqldbServer {
	
	private final static Logger log = LoggerFactory.getLogger(HsqldbServer.class);
	
	private static Server server;
	
	public static void main(String[] args) throws Exception {
		HsqldbServer.start();
	}
	
	public static void start() throws Exception {
		log.info("starting hsql server ...");
		
		server = new Server();
		
		HsqlProperties props = new HsqlProperties();
		props.setProperty("database.0", "mem:platform");
		props.setProperty("dbname.0", "platform");
		props.setProperty("remote_open", true);
		props.setProperty("reconfig_logging", false);

		server.setProperties(props);
		server.start();
		
		Class.forName("org.hsqldb.jdbcDriver");
		Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:platform", "SA", "");
		Statement stmt = conn.createStatement();
		
		stmt.execute(HsqldbConstants.SYSTEM_CONFIG_DDL);
		log.info("created table system_config");
		
		stmt.execute("insert into system_config(name, value) values('admin.page.request.suffix', '.dox')");
		stmt.execute("insert into system_config(name, value) values('admin.jsp.root', '/')");
		
		stmt.execute(HsqldbConstants.TREE_MENU_DDL);
		log.info("created table tree_menu");
		
		stmt.execute("insert into tree_menu(id,text,parent_id,status) values(1,'代码工具',0,'Y')");
//		stmt.execute("insert into tree_menu(id,text,parent_id,status,url) values(2,'DDL2Code',1,'Y','tabs/ddl2code')");
//		stmt.execute("insert into tree_menu(id,text,parent_id,status,url) values(3,'DDL2Bean',1,'Y','tabs/ddl2bean')");
		stmt.execute("insert into tree_menu(id,text,parent_id,status,url) values(4,'DDL2Page',1,'Y','tabs/ddl2page')");
		
		stmt.execute(HsqldbConstants.EXCEPTION_CONFIG_DDL);
		log.info("created table exception config");
		
//		ResultSet rs = stmt.executeQuery("select count(*) from system_config");
//		if(rs.next()){
//			System.out.println(rs.getInt(1));
//		}
	}
	
	public static void stop(){
		server.stop();
	}
}
